package org.apache.sad.core.framework.utils;

import java.lang.reflect.Array;
import java.util.Arrays;

public class EqualsUtil {
    public static int computeHashCode(Object obj) {
        if(obj == null) return 0;
        if(!obj.getClass().isArray()) {
            return obj.hashCode();
        }
        int i = 17;
        int j = Array.getLength(obj);
        for(int k = 0; k < j; k++) {
            Object element = Array.get(obj, k);
            i = 37 * i + (element != null ? computeHashCode(element) : 0);
        }
        return i;
    }

    public static boolean compareObjects(Object source, Object target) {
        if(source == null ) return target == null;
        if(target == null) return false;
        if(source.getClass().isArray()) {
            return compareArrayObjects(source, target);
        } else {
            return source.equals(target);
        }
    }

    public static boolean compareArrayObjects(Object source, Object target)
    {
        if((source instanceof Object[]) && (target instanceof Object[]))
            return Arrays.equals((Object[])(Object[])source, (Object[])(Object[])target);
        if((source instanceof int[]) && (target instanceof int[]))
            return Arrays.equals((int[])(int[])source, (int[])(int[])target);
        if((source instanceof byte[]) && (target instanceof byte[]))
            return Arrays.equals((byte[])(byte[])source, (byte[])(byte[])target);
        if((source instanceof long[]) && (target instanceof long[]))
            return Arrays.equals((long[])(long[])source, (long[])(long[])target);
        if((source instanceof short[]) && (target instanceof short[]))
            return Arrays.equals((short[])(short[])source, (short[])(short[])target);
        if((source instanceof char[]) && (target instanceof char[]))
            return Arrays.equals((char[])(char[])source, (char[])(char[])target);
        if((source instanceof double[]) && (target instanceof double[]))
            return Arrays.equals((double[])(double[])source, (double[])(double[])target);
        if((source instanceof float[]) && (target instanceof float[]))
            return Arrays.equals((float[])(float[])source, (float[])(float[])target);
        if((source instanceof boolean[]) && (target instanceof boolean[]))
            return Arrays.equals((boolean[])(boolean[])source, (boolean[])(boolean[])target);
        else
            return false;
    }
}
